package base.controller.sys;

import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import base.entity.User;
import base.service.sys.FileService;
import base.util.ResultMessage;

/**
 * 文件相关操作请求
 * @author JZH
 *
 */
@Controller
@RequestMapping("file")
public class FileController {

	@Autowired
	private FileService fileService;
	
	/**
	 * 文件上传（表单）
	 * @param request
	 * @param description
	 * @param file
	 */
	@RequestMapping(value="upload1", method=RequestMethod.POST)
	public String fileUpload(HttpServletRequest request, String description, MultipartFile file) {
		//如果文件不为空，写入上传路径
        if(!file.isEmpty()) {
        	User user = (User) request.getSession().getAttribute("LOGIN_USER");
        	ResultMessage<?> message = fileService.uploadFile(description, file, user.getId());
        	if("SUCCESS".equals(message.getResult())) {
        		return "success";
        	} else {
        		return "error/sql";
        	}
        }
        return "error/io";
	}
	
	/**
	 * 文件上传（Ajax）
	 * @param request
	 * @param description
	 * @param file
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="upload2", method=RequestMethod.POST)
	public ResultMessage<?> fileUpload2(HttpServletRequest request, String description, MultipartFile file) {
		//如果文件不为空，写入上传路径
        if(!file.isEmpty()) {
        	User user = (User) request.getSession().getAttribute("LOGIN_USER");
        	ResultMessage<?> message = fileService.uploadFile(description, file, user.getId());
        	return message;
        }
        return ResultMessage.createErrorResultMessage("上传失败");
	}
	
	/**
	 * 文件下载（方式一）
	 * @param request
	 * @param id
	 * @return
	 */
	@RequestMapping(value="download1", method=RequestMethod.GET)
	public ResponseEntity<byte[]> fileDownload(Integer id) {
		return fileService.downloadFile(id);
	}
	
	/**
	 * 文件下载（流方式）
	 * @param response
	 * @param id
	 */
	@RequestMapping(value="download2", method=RequestMethod.GET)
	public void fileDownload2(HttpServletResponse response, Integer id) {
		Map<String, Object> map = fileService.getPathAndNameById(id);
		String filePath = map.get("FILE_PATH").toString() + map.get("FILE_NAME").toString();
		InputStream in = null;
		try {
			in = new FileInputStream(filePath);
			if(null != in) {
				byte[] buffer = new byte[in.available()];
				in.read(buffer);
				in.close();
				// 清空response
		        response.reset();
		        // 设置response的Header
		        response.addHeader("Content-Disposition", "attachment;filename=" + new String(map.get("FILE_NAME").toString().getBytes()));
		        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
		        response.setContentType("application/octet-stream");
		        toClient.write(buffer);
		        toClient.flush();
		        toClient.close();
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
}
